/*
 * @Author: 詹真琦(legendryztachi@gmail.com)
 * @Date: 2022-03-23 17:15:14
 * @LastEditors: 詹真琦(legendryztachi@gmail.com)
 * @LastEditTime: 2022-05-12 17:44:43
 * @FilePath: \code\cwp-front\pc-collaboration\src\handles\handle-list\summary\modules\continue-submit\helper.js
 * @Description: 关于提交的一些操作
 */
/*global workflowModule*/
import { useBaseInfoWithOut } from '@/store/modules/base-info';
import { useSummaryCommentWithOut } from '@/store/modules/summary/comment';
import { useTemplateWithOut } from '@/store/modules/template';
import { useSuperviseSetWithOut } from '@/store/modules/summary/supervise-set';
//富文本的获取提及列表
import { getMentionList } from '@/components/classic-layout/summary/handle-right/components/textarea/components/rich-text/helper';
//文本域的获取提及列表
import { getMentionList as getMentionListByTextArea } from '@/components/atom/at-who/helper';

import  getFormDataFn from '@/helper/form-params-helper';
//弹出框选项
import ChooseHandle from './components/chooseHandle';
//基础信息
const useBaseInfo = useBaseInfoWithOut();
//协同信息
const useSummaryComment = useSummaryCommentWithOut();
//正文信息
const useTemplate = useTemplateWithOut();
//督办
const useSuperviseSet = useSuperviseSetWithOut();
//所有的操作集合
import handleObj, { doHandle } from '@/handles/handle-list/summary';
import globalData from "@/plugins/data";
/**
 * @description: 获取意见相关
 * @param {*}
 * @return {*}
 */
export function getComment() {
  //意见相关-----------------
  const {
    attitude,
    attitudeList,
    isRichText,
    commentText,
    relationDoc: assDocDomain,
    attachments: attFileDomain,
    isPraise: praiseToSummary,
    isHideOpinion: hidden,
    hideOpinionObject,
    textContent,
  } = useSummaryComment;

  return {
    //态度
    attitude: attitudeList.find((d) => d.code === attitude),
    //意见内容
    content: isRichText ? textContent : commentText,
    //推送列表。艾特人。
    //目前又说只需要传memberId
    pushMessageUserIds: (isRichText
      ? getMentionList(commentText)
      : getMentionListByTextArea(commentText)
    ).map((d) => d.memberId),
    //是否点赞
    praiseToSummary,
    //设置富文本内容
    richContent: isRichText ? commentText : '',
    //是否是富文本
    isRichContent: isRichText,
    //附件和关联文档
    assDocDomain,
    attFileDomain,
    //意见隐藏
    hidden,
    //意见隐藏的人员
    showToId: hideOpinionObject.value
    // showToIdText: hideOpinionObject.text,
  };
  //-----------------------
}
/**
 * @description: 获取协同数据。关键点
 * packageOperationId字段是封装了流程以及提交的按钮用，在里面设置
 * pigeonholeId归档选的id字段在提交之后弹窗里面设置
 * @param {Object}btn 按钮数据。没传就是存为草稿
 * @return {Object}协同所有数据
 */
export function getCollaborationData(btn) {
  const params = {};
  //意见相关-----------------
  params.comment = getComment();
  //督办----------
  const {
    detailId,
    superviseAwakeDate,
    superviseTitle,
    supervisorIds,
    supervisorNames,
    isModifySupervise
  } = useSuperviseSet;
  params.superviseSet = {
    detailId,
    superviseAwakeDate,
    superviseTitle,
    supervisorIds,
    supervisorNames,
    isModifySupervise
  };
  //-----------------------

  //跟踪---------
  params.trackSet = useSummaryComment.trackSet;
  //-----------------------

  //处理人信息---------
  params.dealDepartment =
    useSummaryComment.dealDepartmentList[useSummaryComment.dealDepartmentIndex];
  //-----------------------

  //是否归档
  params.isPigeonhole = useSummaryComment.isPigeonhole;
  //密级
  params.secretLevel = useBaseInfo.baseInfo.secretLevel.value;
  //附件和关联文档
  params.assDocDomain = useBaseInfo.relationDocs.atts;
  params.attFileDomain = useBaseInfo.attachments.atts;
  //操作的日志
  params.attachmentLogs = useBaseInfo.attachmentLogs;
  //正文修改类型
  params.modifyType = window.isEditAttOrContent;

  if (btn) {
    //提交code。submitActionOriginal自定义按钮有，handleOriginal一般系统内置按钮有
    params.submitCode = btn.submitActionOriginal || btn.handleOriginal;

    //自定义提交加上id。废除
    //因为他可以改了工作流之后，再点加签给xxx并提交之类的按钮，这时候之前改的也要一并提交
    // params.packageOperationId = btn.id;
  }
  console.log('getCollaborationData', params);

  return params;
}
/**
 * @description: 获取表单数据。参考新建的
 * @param  submitCode 提交类型
 * @param needCheck 是否需要校验表单
 * @param loadingResolve 回调
 * @return {Object}表单所有数据
 */
export async function getFormData(submitCode='',needCheck, loadingResolve=()=>{}) {
  const cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
  if (!cap4) {
    return {};
  }
  //获取表单数据
  let params = {checkNull: needCheck, needCheckRule: needCheck};
  return getFormDataFn(params)
    .then((formData)=>{
       return new Promise(resolve => {
         if (formData) {
           formData.content.isMerge = '1';
           formData.content.needAutoCollect = '1';
           formData.content.optType = submitCode;
           formData.content.needCheckRule = '1';
           // 如果不需要表单校验
           if (!needCheck) {
             formData.content.needCheckRule = '0';
           }
           console.log('formData', formData);
           return  resolve(formData);
         } else {
           //关闭掉全局的loading
           loadingResolve();
           //表单数据获取失败，表单会弹出提示
           resolve();
         }
       })
    })
}
/**
 * @description: 获取工作流数据。参考新建，后边合并
 * @param {Object}formData 表单数据
 * @return {Object}工作流所有数据
 */
export function getWorkflowData(formData) {
  //工作流数据
  const workflowParamData = workflowModule.getWorkflowParams();
  //表单数据、formData，mastrid 在cap4 是同一个值
  if (useBaseInfo.baseInfo.zwIframe.isCap4) {
    workflowParamData.context.formData = formData.content.contentDataId;
    workflowParamData.context.mastrid = formData.content.contentDataId;
    workflowParamData.context.isCAP4 = true;
  }
  workflowParamData.context.affairId = globalData.affairId;
  //应用名称：一般为 collaboration 或者edoc
  workflowParamData.context.appName = 'collaboration';
  return workflowParamData;
}

/**
 * @description: 设置第三方数据
 * @param {Object}btn 当前按钮数据
 * @return {*}
 */
function getThirdpartParamData(btn) {
  return {
    data: btn.getThirdpartParamData ? [btn.getThirdpartParamData] : [],
    thirdPartyContext: useBaseInfo.thirdPartyContext
  };
}

/**
 * @description: 创建提交的数据
 * @param {Object}btn 当前按钮数据
 * @return {Object}最终提交的数据
 */
export async function getCreateParams(btn, resolve, needCheck) {
  const collaborationParams = getCollaborationParams(btn);
  let formParamData = {};
  if (useBaseInfo.baseInfo.zwIframe.isCap4) {
    const {collaborationDealParamData}=collaborationParams;
    formParamData = await getFormData(
      collaborationDealParamData.submitCode !== 'Comment' && needCheck, //不是暂存待办就需要校验
      resolve
    );
  }
  if (!formParamData){
    return;
  }
  return {
    formParamData: { data: formParamData },
    ...collaborationParams
  };
}

/**
 * 不包含表单的协同数据
 * @param btn
 * @param resolve
 * @param needCheck
 * @returns 
 */
export function getCollaborationParams(btn) {
  const collaborationDealParamData = getCollaborationData(btn);
  return {
    collaborationDealParamData,
    thirdpartParamData: getThirdpartParamData(btn),
    //其他数据，比如人脸识别
    otherParamData: useBaseInfo.otherParamData
  };
}

/**
 * @description: 根据当前选择的操作对象，确定执行某项操作或者继续
 * @param {String} code 当前选择的操作的运行名称
 * @param {String} subject 当前选择的操作对象的显示名称
 * @param {Function} resolve
 * @param {Function} reject
 * @param {Function} submitResolve
 * @return {*}
 */
function executeHandle(
  {code: handle, subject: label, codeOriginal: handleOriginal, permissionOperation = {}},
  resolve,
  reject,
  submitResolve
) {
  console.log('态度不同意，执行操作', handle, label);

  //如果是提交就直接继续
  if (handle === 'continueSubmit') {
    resolve();
  } else {
    //指定回退的可选方式
    const {submitStyle} = permissionOperation;
    //否则执行对应操作
    doHandle.call(this, handle, {label, handle, handleOriginal, submitStyle});
    reject();
    submitResolve();
  }
}
/**
 * @description: 如果配置了“不同意操作设置-用户可选”
 * @param {Object}btn 按钮信息。 接口返回的 不同意操作枚举，枚举值：
 * Continue: 继续
 * Terminate: 终止
 * Return: 回退
 * Cancel: 撤销
 * SpecifiesReturn: 指定回退
 * @param {Array}disagreeAction 用户能够选择的不同意操作列表
 * @param {Function}submitResolve 外层遮罩的Promise的resolve
 * @return {Promise}返回一个promise对象，用户选择后resolve，取消reject
 */
export function chooseHandle(disagreeAction, submitResolve) {
  return new Promise((resolve, reject) => {
    //如果只有一个，就直接执行
    if (disagreeAction.length === 1) {
      executeHandle.call(this, disagreeAction[0], resolve, reject, submitResolve);
    } else {
      //有多个，就弹出选择框
      //选项值
      let value = disagreeAction.findIndex((d) => d.isDefault);
      this.$confirm({
        title: $.i18n('common.system.hint.label'),
        // h 参数需保留，渲染需要该参数
        // eslint-disable-next-line no-unused-vars
        content: (h) => <ChooseHandle options={disagreeAction} v-model={value} />,
        closable: true,
        width: 500,
        onOk: () => {
          executeHandle.call(this, disagreeAction[value], resolve, reject, submitResolve);
        },
        onCancel: () => {
          reject();
          //关闭弹窗就中断。关闭外层的loading
          submitResolve();
        }
      });
    }
  });
}
